/**
 * 报销单提交管控
 */
import React, { Component } from "react";
import { Popover, Badge, Modal, message, Radio } from "antd";
import { getDefaultSetOfBook, messages } from "share/common";
import SlideFrameDetail from "containers/expense-reimbursement-control/expense-standard/reimbursement-submission/reimbursement-submission-new";
import TableList from "../table-list";
import requestAndExpenseService from "../request-and-expense-settings.service";
import reimburseService from "../../expense-reimbursement-control/expense-standard/reimbursement/reimbursement.service";
import errorMessage from "share/errorMessage";
import menuRoute from "routes/menuRoute";
import { batchOperations } from "components/template/wrapped-table-params/batch-operations";

class ReimbursementStandard extends Component {
  tableRef = null;

  state = {};

  infoData = {
    dataSource: {
      explain: messages(
        "expense-8.key367"
      ) /*您可在此页面配置报销单提交管控规则，系统根据您配置的规则自动对报销单中各业务实体之间的合理性（如：行程日期外发生的费用不可报销）进行管控。实体包括：发票、费用、行程、单据、关联的申请单、预付款单、合同等*/,
    },
    attributes: [
      {
        title: messages("expense-8.key6") /*说明*/,
        dataIndex: "explain",
        span: 24,
      },
    ],
  };

  slideFrameInfo = {
    title: messages("expense-8.key37") /*报销单提交管控*/,
    content: SlideFrameDetail,
    params: {},
  };

  searchForm = [
    {
      id: "levelCode",
      label: messages("expense-8.key1") /*层级*/,
      component: (
        <Radio.Group>
          <Radio value="ALL">{messages("common.all") /*全部*/}</Radio>
          <Radio value="COMPANY">{messages("expense-8.key2") /*公司*/}</Radio>
          <Radio value="SET_OF_BOOK">{messages("expense-8.key3") /*帐套*/}</Radio>
        </Radio.Group>
      ),
      dataIndex: "levelCode",
      parser: (value) => ({
        levelCode: value !== "ALL" ? value : undefined,
      }),
      tagParser: (value) => {
        if (value === "ALL") {
          return messages("common.all") /*全部*/;
        } else {
          return value === "COMPANY" ? messages("expense-8.key2") /*公司*/ : messages("expense-8.key3") /*帐套*/;
        }
      },
    },
    {
      id: "distLevelOrgIds",
      label: messages("expense-8.key4") /*启用公司*/,
      component: "Chooser",
      props: {
        labelKey: "name",
        valueKey: "id",
        type: "priority_company",
      },
      dataIndex: "companys",
      parser: (value) => ({
        distLevelOrgIds: value ? value.map((item) => item.id) : null,
      }),
    },
  ];

  componentDidMount() {
    this.getSetOfBook();
  }

  getSetOfBook = () => {
    getDefaultSetOfBook().then((res) => {
      if (res.data && res.data.defaultSetOfBooksId) {
        this.slideFrameInfo.params.setOfBook = {
          id: res.data.defaultSetOfBooksId,
          name: res.data.defaultSetOfBooksName,
        };
      }
    });
  };

  columns = [
    {
      title: messages("expense-8.key1") /*层级*/,
      dataIndex: "levelCode",
      width: 120,
      minWidth: 100,
      render: (value) =>
        value === "COMPANY" ? messages("expense-8.key2") /*公司*/ : messages("expense-8.key3") /*帐套*/,
    },
    {
      title: messages("expense-8.key8") /*所属组织*/,
      dataIndex: "levelOrgName",
      minWidth: 180,
      render: (value) => (
        <Popover content={value} placement="topLeft">
          {value}
        </Popover>
      ),
    },
    {
      title: messages("expense-8.key4") /*启用公司*/,
      dataIndex: "companys",
      width: 240,
      minWidth: 180,
      render: (value) => this.renderColumns({ value, dataIndex: "companys" }),
    },
    {
      title: messages("expense-8.key10") /*规则名称*/,
      dataIndex: "name",
      width: 200,
      minWidth: 180,
      render: (value) => (
        <Popover content={value} placement="topLeft">
          {value}
        </Popover>
      ),
    },
    {
      title: messages("expense-8.key104") /*适用单据*/,
      dataIndex: "forms",
      width: 120,
      minWidth: 100,
      render: (value) => this.renderColumns({ value, dataIndex: "forms" }),
    },
    {
      title: messages("expense-8.key114") /*控制力度*/,
      dataIndex: "controlLevel",
      width: 120,
      minWidth: 100,
      render: (value) => this.renderColumns({ value, dataIndex: "controlLevel" }),
    },
    {
      title: messages("expense-8.key116") /*提示内容*/,
      dataIndex: "message",
      width: 240,
      minWidth: 180,
      render: (value) => this.renderColumns({ value, dataIndex: "message" }),
    },
    {
      title: messages("common.column.status") /*状态*/,
      dataIndex: "status",
      width: 120,
      minWidth: 100,
      render: (value) => this.renderColumns({ value, dataIndex: "status" }),
    },
    {
      title: messages("common.operation") /*操作*/,
      dataIndex: "ruleOID",
      width: 120,
      minWidth: 120,
      render: (value, record) => (
        <a disabled={record.readOnly} onClick={(e) => this.deleteRule(e, value)}>
          {messages("common.delete") /*删除*/}
        </a>
      ),
    },
  ];

  deleteRule = (e, ruleOID) => {
    e.stopPropagation();
    Modal.confirm({
      title: messages("expense-8.key18") /*确认删除？*/,
      content: messages("expense-8.key368") /*确认删除该设置*/,
      onOk: () => {
        reimburseService
          .deleteRule(ruleOID)
          .then(() => {
            message.success(
              messages("common.delete.success", {
                arg1: "",
              }) /*{arg1} 删除成功*/
            );
            this.advancedTableRef.getList();
          })
          .catch((e) => {
            errorMessage(e.response);
            this.setState({ loading: false });
          });
      },
    });
  };

  //todo
  service = (page, size, searchParams) => {
    let params = {
      size,
      page,
      businessType: 1002,
      ...searchParams,
    };
    return requestAndExpenseService.getReimbursementList(params);
  };

  handleAfterClose = (res) => {
    if (res) {
      let url = menuRoute.getPageUrlByKey("reimbursement-submission-detail").replace(`:ruleOID`, res);
      this.context.router.push(url);
    }
  };

  renderColumns = (params) => {
    const { dataIndex, value } = params;

    if (dataIndex === "status") {
      return (
        <Badge
          status={value ? "success" : "error"}
          text={value ? messages("expense-8.key83") /*启用temp*/ : messages("expense-8.key84") /*禁用temp*/}
        />
      );
    }

    if (dataIndex === "forms") {
      return value && value.length ? (
        <Popover placement="topLeft" content={value.map((item) => item.formName).join("、")}>
          {value.map((item) => item.formName).join("、")}
        </Popover>
      ) : (
        messages("expense-8.key9")
      ) /*通用*/; /*通用*/
    }

    if (dataIndex === "controlLevel") {
      return value === "WARN" ? messages("expense-8.key95") /*警告*/ : messages("expense-8.key96") /*禁止*/; /*禁止*/
    }

    if (dataIndex === "message") {
      return (
        <Popover placement="topLeft" content={value}>
          {value}
        </Popover>
      );
    }

    if (dataIndex === "companys") {
      return value && value.length ? (
        <Popover placement="topLeft" content={value.map((item) => item.name).join("、")}>
          {value.map((item) => item.name).join("、")}
        </Popover>
      ) : (
        messages("expense-8.key9")
      ) /*通用*/; /*通用*/
    }
  };

  render() {
    let tableParams = batchOperations(
      {
        rowKey: "ruleOID",
      },
      [
        {
          type: "DELETE",
          service: requestAndExpenseService.batchDeleteSubmissionControl,
          onOk: () => this.advancedTableRef.getList(),
          extraParams: { businessType: 1002 },
        },
        {
          type: "ENABLE",
          service: requestAndExpenseService.batchOpenOrCloseSubmissionControl,
          onOk: () => this.advancedTableRef.getList(),
          extraParams: { businessType: 1002 },
        },
        {
          type: "DISABLE",
          service: requestAndExpenseService.batchOpenOrCloseSubmissionControl,
          onOk: () => this.advancedTableRef.getList(),
          extraParams: { businessType: 1002 },
        },
      ],
      this
    );
    return (
      <div className="tags-control">
        <TableList
          infoData={this.infoData}
          slideFrameInfo={this.slideFrameInfo}
          subPageInfo={{
            key: "reimbursement-submission-detail",
            replaceParams: ["ruleOID"],
          }}
          afterClose={this.handleAfterClose}
          tableParams={{
            rowKey: "ruleOID",
            searchForm: this.searchForm,
            columns: this.columns,
            service: this.service,
            tableName: "expense-claim-business-control",
            onRef: (ref) => (this.advancedTableRef = ref),
            ...tableParams,
          }}
        />
      </div>
    );
  }
}

ReimbursementStandard.contextTypes = {
  router: React.PropTypes.object,
};

export default ReimbursementStandard;
